package com.airsystem.pos.bengkel.service.parser;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;

import com.airsystem.pos.bengkel.entity.DetailKendaraan;
import com.airsystem.pos.bengkel.entity.DetailSparepart;
import com.airsystem.pos.bengkel.entity.JenisSparepart;
import com.airsystem.pos.bengkel.interfaces.IParser;

/**
 * @author Fanny Irawan Sutawanir (fannyirawans@gmail.com)
 */
public class SparepartParser implements IParser<List<DetailSparepart>, Iterable<?>> {
	private static final Logger LOG = Logger.getLogger(SparepartParser.class.getSimpleName());

	public List<DetailSparepart> doParse(Iterable<?> data) {
		List<DetailSparepart> list = new LinkedList<DetailSparepart>();

		for (Object result : data) {
			if (isArray(result)) {
				Object[] objects = (Object[]) result;
				DetailSparepart detailSparepart = null;

				for (Object item : objects) {
					if (isDetailSparepartInstance(item)) {
						detailSparepart = (DetailSparepart) item;
					} else if (isJenisSparepartInstance(item)) {
						detailSparepart.setJenis_sparepart((JenisSparepart) item);
					} else if (isKendaraanInstance(item)) {
						detailSparepart.setDetail_kendaraan((DetailKendaraan) item);
					} else {
						LOG.info("Instance result is " + item.toString());

						continue;
					}

					continue;
				}

				list.add(detailSparepart);
			} else {
				DetailSparepart detailSparepart = null;

				if (isDetailSparepartInstance(result)) {
					detailSparepart = (DetailSparepart) result;
					list.add(detailSparepart);
				} else {
					LOG.info("No array result is " + result.toString());
				}
			}
		}

		return list;
	}

	private boolean isArray(Object object) {
		return object.getClass().isArray();
	}

	private boolean isDetailSparepartInstance(Object object) {
		return (object instanceof DetailSparepart);
	}

	private boolean isJenisSparepartInstance(Object object) {
		return (object instanceof JenisSparepart);
	}

	private boolean isKendaraanInstance(Object object) {
		return (object instanceof DetailKendaraan);
	}
}